package com.zoo.buyor.user.service.impl;

import com.zoo.buyor.common.constant.RedisKey;
import com.zoo.buyor.common.utils.JwtUtils;
import com.zoo.buyor.common.utils.RedisUtils;
import com.zoo.buyor.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    public static final int TOKEN_EXPIRE_DAYS = 3;
    private static final int TOKEN_RENEWAL_DAYS = 2;
    @Autowired
    JwtUtils jwtUtils;

    @Override
    public String loginToken(Long uid) {
        String token = jwtUtils.createToken(uid);
        String redisKey = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
        RedisUtils.set(redisKey, token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }

    @Override
    public boolean verify(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return false;
        }
        String redisKey = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
        String realToken = RedisUtils.getStr(redisKey);
        return Objects.equals(token, realToken);//有可能token失效了，需要校验是不是和最新token一致
    }
    @Override
    public Long getValidUid(String token) {
        boolean verify = verify(token);
        return verify ? jwtUtils.getUidOrNull(token) : null;
    }

    @Async
    @Override
    public void renewalTokenIfNecessary(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return;
        }
        String key = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
        long expireDays = RedisUtils.getExpire(key, TimeUnit.DAYS);
        if (expireDays == -2) {//不存在的key
            return;
        }
        if (expireDays < TOKEN_RENEWAL_DAYS) {//小于一天的token帮忙续期
            RedisUtils.expire(key, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        }
    }

}
